package com.ciwong.epaper.modules.epaper.ui;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;

import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Copyright © 深圳市倍轻松科技股份有限公司
 *
 * @Filname : AiSpokenActivity.java
 * @Author : Penghao
 * @Create : 2025/8/21 14:09
 * @Description :
 * @Version : v1.0
 **/

public class AiSpokenActivity extends BaseActivity implements View.OnClickListener {

    private BridgeWebView bridgeWebView;

    private CWDialog getRecordPermissDialog;

    public void onEventMainThread(SubmitEvent submitEvent) {
        final String id = submitEvent.getId();
        final String callbackId = submitEvent.getCallbackId();
        Log.e(TAG, "onEventMainThread id: " + id);
        Log.e(TAG, "onEventMainThread callbackId: " + callbackId);

    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    protected int setView() {
        return R.layout.activity_ai_spoken_main;
    }

    @Override
    protected void findViews() {
        bridgeWebView = findViewById(R.id.publish_dk_webview);
        String url = "https://m.teacher.jiaofuyun.com/chatAi#/?origin=android&userId="+ EApplication.getInstance().getUserInfoBase().getUserId();;

        bridgeWebView.setDefaultHandler(new DefaultHandler());
        bridgeWebView.setWebChromeClient(new WebChromeClient() {
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
                this.openFileChooser(uploadMsg);
            }

            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
                this.openFileChooser(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            }
        });

        bridgeWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                bridgeWebView.registerHandler("webStartRecord", new BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Log.e("callUpdateRecord","webStartRecord");
                    }
                });
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                CWLog.e("onPageFinished ", url);
                bridgeWebView.registerHandler("webStartRecord", new BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Log.e("callUpdateRecord","webStartRecord");
                    }
                });
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        WebSettings webSettings = bridgeWebView.getSettings();
        webSettings.setAllowContentAccess(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setDomStorageEnabled(true);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            webSettings.setAllowUniversalAccessFromFileURLs(true);
//        }
//        webSettings.setPluginState(WebSettings.PluginState.ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        //String url = "http://192.168.31.57:9018/";
//        bridgeWebView.setDefaultHandler(new DefaultHandler());
//        bridgeWebView.setWebChromeClient(new WebChromeClient());
//
//        Log.d(TAG, url);
//        bridgeWebView.setDefaultHandler(new DefaultHandler());
//        bridgeWebView.setWebChromeClient(new WebChromeClient());
//
//        bridgeWebView.getSettings().setJavaScriptEnabled(true);
//        bridgeWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        bridgeWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
//        bridgeWebView.getSettings().setAllowFileAccess(true);
//        bridgeWebView.getSettings().setLoadWithOverviewMode(true);
//        bridgeWebView.getSettings().setUseWideViewPort(true);
//        bridgeWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        bridgeWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置webSettings，允许其加载混合网络协议内容

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            bridgeWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }

        bridgeWebView.loadUrl(url);
        bridgeWebView.registerHandler("webStartRecord", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.e("callUpdateRecord","webStartRecord");
            }
        });
        //设置webSettings，允许其加载混合网络协议内容
//        bridgeWebView.setWebViewClient(new MyWebViewClient(bridgeWebView));


    }

    class MyWebChromeClient extends WebChromeClient {
        private View myView = null;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        // 全屏
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
//            ViewGroup parent = (ViewGroup) bridgeWebView.getParent();
//            parent.removeView(bridgeWebView);
//            myView = view;
        }

        // 退出全屏
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
        }
    }


    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });

        //通知录音
//        bridgeWebView.registerHandler("callUpdateRecord", new BridgeHandler() {
//
//            @Override
//            public void handler(String data, CallBackFunction function) {
//               Log.e("callUpdateRecord","callUpdateRecord");
//            }
//        });
//
//        bridgeWebView.registerHandler("webStartRecord", new BridgeHandler() {
//
//            @Override
//            public void handler(String data, CallBackFunction function) {
//                Log.e("callUpdateRecord","webStartRecord");
//            }
//        });

    }
    @Override
    public void finish() {
        if (null != bridgeWebView && bridgeWebView.canGoBack()) {
            bridgeWebView.goBack();// 返回前一个页面
        } else {
            super.finish();
        }
    }
    /**
     * 使用录音，判断权限
     */
    public boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    SentenceRepeatActivity.CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            CWLog.e("权限申请 flag = ", flag + "");
                        }
                    });
        } else {

        }
        return true;
    }


    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(AiSpokenActivity.this, Manifest.permission.RECORD_AUDIO);
        CWLog.e("isHavePermiss = ", isHavePermiss + "");
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(AiSpokenActivity.this);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(AiSpokenActivity.this.getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();


                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();

    }

    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            if ("onPageFinished".equals(id)) {
                try {

                    onPageFinishedUrl.add((String) data);

                } catch (IllegalStateException e) {

                }
            }
            return super.onMessage(id, data);
        }
    };

    @Override
    protected void loadData() {
        showH5View();
        String url = "https://m.teacher.jiaofuyun.com/chatAi#/?origin=android&userId="+ EApplication.getInstance().getUserInfoBase().getUserId();;
//        cordovaWebView.loadUrl(url);
//        showBackBar();
    }


    private void showH5View() {
        hideTitleBar();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (null != bridgeWebView) {
            bridgeWebView.destroy();
        }
        super.onDestroy();
    }
}
